<script setup>
import { ref, onMounted, watch, onUnmounted, computed, toRefs } from 'vue'
import Chart from 'chart.js/auto'

const props = defineProps({
  correctRespond: {
    type: Number,
    default: 0
  },
  wrongNum: {
    type: Number,
    default: 0
  },
  unfinishedWords: {
    type: Number,
    default: 0
  }
})

const { correctRespond, wrongNum, unfinishedWords } = toRefs(props)

const accuracyPercent = computed(() => {
  const total = correctRespond.value + wrongNum.value
  return total > 0 ? (correctRespond.value / total * 100).toFixed(1) : 0
})

const chartRef = ref(null)
const chartInstance = ref(null)

const data = ref({
  labels: [`答对${correctRespond.value}`, `未完成${unfinishedWords.value}`, `答错${wrongNum.value}`],
  datasets: [{
    data: [correctRespond.value, unfinishedWords.value, wrongNum.value],
    backgroundColor: ['#C4FFAF', '#E8E8E8', '#FFC4C4'],
    borderWidth: 0
  }]
})

const centerText = {
  id: 'centerText',
  beforeDraw(chart) {
    const { ctx } = chart
    const text = `准确率 ${accuracyPercent.value}%`

    ctx.save()
    ctx.font = 'bold 20px Arial'
    ctx.fillStyle = '#4A4A4A'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(text, chart.width / 2, chart.height / 2.2)
    ctx.restore()
  }
}

const updateChart = () => {
  if (chartInstance.value) {
    chartInstance.value.destroy()
  }

  chartInstance.value = new Chart(chartRef.value.getContext('2d'), {
    type: 'doughnut',
    data: data.value,
    plugins: [centerText],
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            boxWidth: 10,
            padding: 20
          }
        }
      },
      cutout: '70%',
      animation: {
        duration: 0
      }
    }
  })
}

watch([correctRespond, wrongNum, unfinishedWords], ([newCorrect, newWrong, newUnfinished]) => {
  data.value = {
    labels: [`答对${newCorrect}`, `未完成${newUnfinished}`, `答错${newWrong}`],
    datasets: [{
      data: [newCorrect, newUnfinished, newWrong],
      backgroundColor: ['#C4FFAF', '#E8E8E8', '#FFC4C4'],
      borderWidth: 0
    }]
  }
  updateChart()
}, { deep: true })

onMounted(updateChart)
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.destroy()
  }
})
</script>

<template>
  <div class="chart-container">
    <canvas ref="chartRef"></canvas>
  </div>
</template>

<style scoped>
.chart-container {
  width: 250px;
  height: 250px;
  position: relative;
}
</style>
